<?php
 
require_once('FirePHPCore/fb.php');
require 'vendor/autoload.php';
use Imagine\Image\Box;
use Imagine\Image\Point;


   
   class SimpleImageManipulator {
   	
	
	
	function uploadFile($img) {
		$directory = $_POST['directory'];
		$filename = $_POST['filename'];
		
		$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
		
		// Bucket Name
		$bucket="chokushoku";
		if (!class_exists('S3'))require_once('vendor/s3/S3.php');
		
		
		
		$s3 = new S3(awsAccessKey, awsSecretKey);
		//$s3->putBucket($bucket, S3::ACL_PUBLIC_READ);
		
		$msg='';
		if($_SERVER['REQUEST_METHOD'] == "POST")
		{
			$name = $_FILES['file']['name'];
			$size = $_FILES['file']['size'];
			$tmp = $_FILES['file']['tmp_name'];
			$ext = $this->getExtension($name);
			
			if($img){
				$tmp = $img;
			}
			
			
			
			if(strlen($name) > 0)
			{
			// File format validation
				if(in_array($ext,$valid_formats))
				{
				// File size validation
					if($size<(1024*1024))
					{
						//Rename image name. 
						$actual_image_name = $directory.$filename.".".$ext;
			
						if($s3->putObjectFile($tmp, $bucket , $actual_image_name, S3::ACL_PUBLIC_READ) )
						{
							$msg = "S3 Upload Successful."; 
							$s3file='http://'.$bucket.'.s3.amazonaws.com/'.$actual_image_name;
							$msg = 1;
							$src = $s3file;
							//echo json_encode(array('status' => '1', 'src' => $s3file));

							//echo "<img src='$s3file'/>";
							//echo 'S3 File URL:'.$s3file;
						}
						else
							//$msg = "S3 Upload Fail.";
							$msg = 2;
						}
					else
						//$msg = "Image size Max 1 MB";
						$msg = 3;
					}
				else
					//$msg = "Invalid file, please upload image file.";
					$msg = 4;
				}

			}
			if($msg)echo json_encode(array('status' => $msg, 'src' => $src));
		
		}	
	
	function getExtension($str) 
	{
		$i = strrpos($str,".");
		if (!$i) { return ""; }
		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);
		return $ext;
	}
	
	
	
    function resizeIconToThumb() {
    	//print_r($_POST);
		
    	$this->resize(100, 100);
	}

	function resizeIconToBusinessIcon(){
		$this->resize(250, 250);
	}
	
	function resizeToMenuItem(){
		$this->resize(400, 400);
	}
	
	
	
	function resize($finalW, $finalH){
		$coords = json_decode($_POST['coords']);

		
		$x = $coords->x;
		$y = $coords->y;
		$w = $coords->w;
		$h = $coords->h;
		
		
		
		$file = $_FILES['file']['tmp_name'];
		$name = $_FILES['file']['name'];
		$size = $_FILES['file']['size'];
		$ext = $this->getExtension($name);
		
		
		$imagine = new Imagine\Gd\Imagine();

		$image = $imagine->open($file);
		

		 $image->crop(new Point($x, $y), new Box($w, $h))
		 	->resize(new Box($w, $h))
			->resize(new Box($finalW, $finalH))
			->save(sys_get_temp_dir()."/".time().".".$ext);
			
		$this->uploadFile(sys_get_temp_dir()."/".time().".".$ext);
	}
	
	function delete(){
		if (!class_exists('S3'))require_once('vendor/s3/S3.php');
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			$s3 = new S3(awsAccessKey, awsSecretKey);
			$bucket="chokushoku";
			$uri = $_POST['filename'];
			$result = $s3->deleteObject($bucket, $uri);
			//echo $result;
			echo json_encode(array('status' => 1, 'src' => ''));
		}else{
			//echo "sandwiches";
		}
	}
	
	function deleteBulk(){
		if (!class_exists('S3'))require_once('vendor/s3/S3.php');
		if($_SERVER['REQUEST_METHOD'] == "POST"){
			$bulk = $_POST['bulk'];
			foreach($bulk as $val) {
				$s3 = new S3(awsAccessKey, awsSecretKey);
				$bucket="chokushoku";
				$uri = $val;
				$result = $s3->deleteObject($bucket, $uri);
				//echo $result;
			}
			echo json_encode(array('status' => 1, 'src' => ''));
		}else{
			//echo "sandwiches";
		}
	}
	
	function route(){
		$uploadType = $_POST['uploadType'];
		if(!$uploadType){
			$rest_json = file_get_contents("php://input");
			$_POST = json_decode($rest_json, true);
			$uploadType = $_POST['uploadType'];
		}
		switch($uploadType){
			case 'user_thumb':
				$this->resizeIconToThumb();
			break;
			case 'remove_from_s3':
				$this->delete();
			break;
			case 'remove_bulk_from_s3':
				$this->deleteBulk();
			break;
			case 'business_icon':
				$this->resizeIconToBusinessIcon();
			break;
			case 'menu_item':
				$this->resizeToMenuItem();
			break;
		}
	}
	
   }
	//AWS access info
	if (!defined('awsAccessKey')) define('awsAccessKey', 'AKIAJ54CXLX2MA52MSAA');
	if (!defined('awsSecretKey')) define('awsSecretKey', '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');
   $api = new SimpleImageManipulator;
   $api->route();
   
?>